package cn.school.workflow.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.school.classManage.dao.SchoolClassDao;
import cn.school.classManage.vo.SchoolClassVO;
import cn.school.common.utils.SysUserUtils;
import cn.school.notice.entity.SchoolNotice;
import cn.school.notice.service.SchoolNoticeService;
import cn.school.student.dao.StudentInfoDao;
import cn.school.student.entity.StudentInfo;
import cn.school.workflow.dao.ViolativeApplyDao;
import cn.school.workflow.service.ViolativeApplyService;
import cn.school.workflow.service.WorkFlowCommonService;
import cn.school.workflow.vo.ViolativeApplyVO;
import cn.school.workflow.vo.ViolativeApplysVO;
import cn.school.workflow.vo.WorkFlowVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * 违纪服务
 */
@Service
public class ViolativeApplyServiceImpl extends ServiceImpl<ViolativeApplyDao, ViolativeApplyVO> implements ViolativeApplyService {

	@Autowired
	private WorkFlowCommonService workFlowCommonService;
	@Autowired
	private SchoolClassDao schoolClassDao;
	@Autowired
	private StudentInfoDao studentInfoDao;
	@Autowired
	private SchoolNoticeService schoolNoticeService;
	@Autowired
	private ViolativeApplyDao violativeApplyDao;

	@Override
	public IPage<ViolativeApplyVO> findViolativeApplyPageList(ViolativeApplyVO vo) {
		LambdaQueryWrapper<ViolativeApplyVO> wrapper = new LambdaQueryWrapper<>(vo);
		wrapper.eq(ViolativeApplyVO::getTenantId, SysUserUtils.getSysUser().getTenantId());
		if (!StringUtils.isEmpty(vo.getApplyNo())) {
			wrapper.eq(ViolativeApplyVO::getApplyNo, vo.getApplyNo());
		}
		wrapper.orderByDesc(ViolativeApplyVO::getCreateTime);
		return page(new Page<>(vo.getPageNum(), vo.getPageSize()), wrapper);
	}

	@Override
	public PageInfo getList(ViolativeApplysVO vo) {
		PageHelper.startPage(vo.getPageNum(),vo.getPageSize());
		List<ViolativeApplyVO> list = violativeApplyDao.getList(vo);
		PageInfo pageInfo = new PageInfo(list);
		return pageInfo;
	}

	@Override
	public boolean cancelViolativeApply(WorkFlowVO vo) {
		LambdaQueryWrapper<ViolativeApplyVO> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(ViolativeApplyVO::getProcessId, vo.getProcessInstanceId());
		ViolativeApplyVO applyVO = new ViolativeApplyVO();
		applyVO.setApplyStatus("2");//撤销流程
		this.baseMapper.update(applyVO, wrapper);
		return workFlowCommonService.cancelApply(vo.getProcessInstanceId(), vo.getApplyDesc());
	}

	@Override
	public int createViolativeApply(ViolativeApplyVO vo) {
		String username = SysUserUtils.getSysUser().getUsername();
		if (vo.getApplyStatus() != null && Integer.valueOf(vo.getApplyStatus()) > 1) {
			return -1;//已经通报过的违纪不能被修改
		}
		int num = 0;
		if (StringUtils.isEmpty(vo.getId())) {
			String applyNo = "VI_" + DateUtil.format(new Date(), "yyyyMMddHHmmssSSS");
			vo.setApplyNo(applyNo);
			vo.setCreateBy(username);
			vo.setCreateTime(new Date());
			vo.setTenantId(SysUserUtils.getSysUser().getTenantId());
			num = this.baseMapper.insert(vo);
		} else {
			vo.setCreateBy(username);
			vo.setCreateTime(new Date());
			num = this.baseMapper.updateById(vo);
		}
		//创建申请单
		return num;
	}

	/**
	 * 查询申请单详情
	 *
	 * @param processInstanceId
	 * @return
	 */
	@Override
	public ViolativeApplyVO findViolativeApplyDetail(Long processInstanceId) {
		LambdaQueryWrapper<ViolativeApplyVO> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(ViolativeApplyVO::getProcessId, processInstanceId);
		return this.baseMapper.selectOne(wrapper);
	}

	/**
	 * 违纪处理
	 *
	 * @param vo
	 * @return
	 */
	@Override
	public int violativeProcess(ViolativeApplyVO vo) {
		int noticeId = 0;
		if (vo.getApplyStatus().equals("2")) {
			SchoolNotice schoolNotice = new SchoolNotice();
			schoolNotice.setTitle(vo.getTitle());
			schoolNotice.setGrade(vo.getGrade());
			schoolNotice.setClassIds(vo.getClassIds());
			schoolNotice.setNoticeType(vo.getNoticeType()+"");
			schoolNotice.setNoticeContent(vo.getNoticeContent());
			schoolNotice.setReleaseScopeNotice(vo.getReleaseScopeNotice());
			schoolNotice.setIsNoticeStudent(vo.getIsNoticeStudent());
			schoolNotice.setNoticeType("2");
			schoolNotice.setStatus(1);
			schoolNotice.setTenantId(SysUserUtils.getSysUser().getTenantId());
			noticeId = schoolNoticeService.insert(schoolNotice);
		}

		int num = 0;
		if (!StringUtils.isEmpty(vo.getIds())) {
			String[] ids = vo.getIds().split(",");
			for (String id : ids) {
				vo.setId(Long.valueOf(id));
				vo.setModifyTime(new Date());
				vo.setModifyBy(SysUserUtils.getSysUser().getUsername());
				vo.setNoticeId(noticeId);
				this.baseMapper.updateById(vo);
				num++;
			}
		}

		return num;
	}

	/**
	 * 查询全部班级
	 *
	 * @return
	 */
	@Override
	public List<SchoolClassVO> findClassAll() {
		LambdaQueryWrapper<SchoolClassVO> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(SchoolClassVO::getStatus, "1");
		wrapper.eq(SchoolClassVO::getTenantId, SysUserUtils.getSysUser().getTenantId());
		wrapper.ne(SchoolClassVO::getIsGraduation, "1");
		return schoolClassDao.selectList(wrapper);
	}

	@Override
	public List<StudentInfo> findStudentByClassId(String classId) {
		LambdaQueryWrapper<StudentInfo> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(StudentInfo::getClassId, classId);
		return studentInfoDao.selectList(wrapper);
	}

	@Override
	public Map<String, List<Object>> violativeApplyLastSenvenDayList() {
		List<Map> list = this.baseMapper.getListByLastSenvenDay(SysUserUtils.getSysUser().getTenantId());
		Map<String, Integer> dbResultMap = new HashMap<>();
		if (list != null && list.size() != 0) {
			for (Map map : list) {
				dbResultMap.put((String) map.get("viapDate"), Integer.valueOf(map.get("viapCount")+""));
			}
		}

		// 遍历开始日期
		Date beginDate = Calendar.getInstance().getTime();
		Calendar beginCalendar = Calendar.getInstance();
		beginCalendar.setTime(beginDate);
		beginCalendar.add(Calendar.DATE, -7);
		// 遍历结束日期(不含当天)
		Date endDate = Calendar.getInstance().getTime();   // 遍历结日期
		Calendar endCalendar = Calendar.getInstance();
		endCalendar.setTime(endDate);

		// 封装数据
		List<Object> dayList = new ArrayList<>();
		List<Object> countList = new ArrayList<>();

		while (true) {
			String tempStrDate = DateUtil.format(beginCalendar.getTime(), "yyyy-MM-dd");
			dayList.add(tempStrDate);
			if (dbResultMap.containsKey(tempStrDate)) {
				countList.add(dbResultMap.get(tempStrDate));
			} else {
				countList.add(0);
			}

			// 结束日期退出
			beginCalendar.add(Calendar.DATE, 1);
			if (DateUtil.format(beginCalendar.getTime(), "yyyy-MM-dd")
					.equals(DateUtil.format(endCalendar.getTime(), "yyyy-MM-dd"))) {
				break;
			}

		}


		Map<String, List<Object>> resultMap = new HashMap<>();
		resultMap.put("dayList", dayList);
		resultMap.put("countList", countList);

		return resultMap;
	}
}
